package celcatSynchronizer;

import com.google.gdata.client.calendar.CalendarQuery;
import com.google.gdata.client.calendar.CalendarService;
import com.google.gdata.data.DateTime;
import com.google.gdata.data.calendar.CalendarEntry;
import com.google.gdata.data.calendar.CalendarEventEntry;
import com.google.gdata.data.calendar.CalendarEventFeed;
import com.google.gdata.data.calendar.CalendarFeed;
import java.net.URL;
import java.util.ArrayList;
import java.util.GregorianCalendar;

/**
 * Interfacage de la Google Calendars API pour les besoins de notre programme.
 */
public class GoogleInterface
{
	private CalendarService m_calendarService;
	
	/**
	 * Constructeur.
	 * @param p_login Le login de connexion.
	 * @param p_password Le mot de passe de connexion.
	 */
	public GoogleInterface(String p_login, String p_password) throws Exception
	{
		m_calendarService = new CalendarService("googleCalendars");
		m_calendarService.setReadTimeout(10000);
		m_calendarService.setUserCredentials(p_login, p_password);
	}
	
	/**
	 * Retourne les calendriers du compte.
	 * @return Les calendriers du compte.
	 */
	public ArrayList<CalendarEntry> getCalendars() throws Exception
	{		
		CalendarFeed feed = m_calendarService.getFeed(new URL("https://www.google.com/calendar/feeds/default/allcalendars/full"), CalendarFeed.class);
		return new ArrayList<CalendarEntry>(feed.getEntries());
	}
	
	/**
	 * Retourne les évènements du calendrier donné.
	 * @param p_entry Calendrier dont on veut les évènements.
	 * @return Les évènements du calendrier donné.
	 */
	public ArrayList<CalendarEventEntry> getEvents(CalendarEntry p_entry) throws Exception
	{
		URL feedUrl = new URL(p_entry.getLink("alternate", "application/atom+xml").getHref());
		CalendarQuery query = new CalendarQuery(feedUrl);
		query.setMaxResults(Integer.MAX_VALUE);
		
		GregorianCalendar gc = new GregorianCalendar();
		gc.setTimeInMillis(Long.parseLong(CelcatSynchronizer.config.getProperty("startWeek")));

		DateTime dateTime = new DateTime(gc.getTimeInMillis());
		query.setMinimumStartTime(dateTime);
		
		gc.add(GregorianCalendar.YEAR, 1);
		gc.add(GregorianCalendar.DAY_OF_MONTH, -1);
		dateTime.setValue(gc.getTimeInMillis());
		query.setMaximumStartTime(dateTime);
		
		CalendarEventFeed feed = m_calendarService.getFeed(query, CalendarEventFeed.class);
		return new ArrayList<CalendarEventEntry>(feed.getEntries());
	}
}
